package com.ibest.base.expand;

import com.alibaba.fastjson.JSONObject;
import com.ibest.base.constant.CacheConstant;
import com.ibest.base.entity.CanalBinlogBean;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.LocalCachedMapOptions;
import org.redisson.api.RLocalCachedMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
public class LocalCacheHandler implements Handler{
    @Resource
    private RedissonClient redissonClient;
    @Value("${ibest.client.topic-name}")
    private String topicName;

    @Override
    public void handle(CanalBinlogBean canalBinlogBean) {
        log.info("本地缓存处理类：{}",canalBinlogBean);
        String type = canalBinlogBean.getType();
        String tableName=canalBinlogBean.getTable();
        List<String> pks=canalBinlogBean.getPkNames();
        List<JSONObject> jsonObjectList=canalBinlogBean.getData();
        RLocalCachedMap<String,Object> localCachedMap=redissonClient.getLocalCachedMap(topicName, LocalCachedMapOptions.defaults());
        if("INSERT".equals(type) || "UPDATE".equals(type)){
            jsonObjectList.stream().forEach(item->{
                StringBuffer idKey=new StringBuffer();
                pks.stream().forEach(item2->{
                    idKey.append(tableName);
                    idKey.append(CacheConstant.SEP_KEY);
                    idKey.append(item.getString(item2));
                });
                localCachedMap.put(idKey.toString(),item);
            });
        }else if ("DELETE".equals(type)) {
            jsonObjectList.stream().forEach(item->{
                StringBuffer idKey=new StringBuffer();
                pks.stream().forEach(item2->{
                    idKey.append(tableName);
                    idKey.append(CacheConstant.SEP_KEY);
                    idKey.append(item.getString(item2));
                });
                localCachedMap.remove(idKey.toString());
            });
        }
    }
}
